package com.imooc.springboot.dubbo.nilinili.consumer.handler;


import com.imooc.springboot.dubbo.nilinili.res.CodeEnum;
import com.imooc.springboot.dubbo.nilinili.res.ResultFactory;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.Set;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = RuntimeException.class)
    public String handleAuthor(RuntimeException e) {
        log.error("系统错误！");
        e.printStackTrace();
        return ResultFactory.createResult(CodeEnum.FAIL, e.getMessage());
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = SignatureException.class)
    public String handleTokenException(SignatureException e) {
        log.error("拦截到无效token");
        return ResultFactory.createResult(CodeEnum.FAIL, "token无效");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = MalformedJwtException.class)
    public String handleMalformedJwtException(MalformedJwtException e) {
        log.error("拦截到无效token");
        return ResultFactory.createResult(CodeEnum.FAIL, "token无效");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler(value = ExpiredJwtException.class)
    public String handleExpiredJwtException(ExpiredJwtException e) {
        log.error("拦截到无效token");
        return ResultFactory.createResult(CodeEnum.FAIL, "token已过期");
    }

    @ResponseStatus(HttpStatus.OK)
    @ExceptionHandler({ConstraintViolationException.class, BindException.class})
    public String validateException(Exception e, HttpServletRequest request) {
        String msg = null;
        if (e instanceof ConstraintViolationException) {
            ConstraintViolationException constraintViolationException = (ConstraintViolationException) e;
            Set<ConstraintViolation<?>> violations = constraintViolationException.getConstraintViolations();
            ConstraintViolation<?> next = violations.iterator().next();
            msg = next.getMessage();
        } else if (e instanceof BindException) {
            BindException bindException = (BindException) e;
            msg = bindException.getBindingResult().getFieldError().getDefaultMessage();
        }
        return ResultFactory.createResult(CodeEnum.ERROR, msg);
    }
}
